package com.sinog.front.controller.biz.statistic;

import com.sinog.core.model.UploadAppendixFile;
import com.sinog.core.model.UserDTO;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.feign.biz.UploadAppendixFileFeignService;
import com.sinog.front.feign.biz.statistic.StatisticService;
import com.sinog.front.service.user.UserFacade;
import com.sinog.front.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc 之前系统全部统计分析
 * @author hak
 * @date 2020年2月23日 7:22
 */
@Slf4j
@RestController
public class StatisticController {

    @Resource
    private UserFacade userFacade;
    @Resource
    private UploadAppendixFileFeignService uploadAppendixFileFeignService;
    @Resource
    private StatisticService statisticService;

    /**
     * 判断文件是否存在
     * @param request request
     * @param filepath filepath
     * @return Result
     */
    @RequestMapping("/azbj/sjtjfx/bgsc/ifFileExist")
    public Result ifFileExist(HttpServletRequest request,String filepath) {
        String path = FileUtil.getFileTemplatePath();
        File file = new File(path + filepath);
        if(!file.exists()) {
            return Result.failure(ReturnCode.FAILURE);
        } else {
            return Result.success();
        }
    }
    /**
     * 下载文件 /报告生成文件下载、下载支持文件(视频、pdf)、
     * @param request request
     * @param resp resp
     * @param fileUrl fileUrl
     * @param fileName fileName
     */
    @RequestMapping("/azbj/sjtjfx/bgsc/downloadFile")
    public void downloadFile(HttpServletRequest request,HttpServletResponse resp,String fileUrl,String fileName) {
        PrintWriter writer = null;
        boolean fileUrlBoolean = StringUtils.isBlank(fileUrl) || fileUrl.contains("/") || !fileUrl.contains(".");
        boolean fileNameBoolean = StringUtils.isBlank(fileName) || fileName.contains("/") || !fileName.contains(".");
        if(fileUrlBoolean || fileNameBoolean) {
            try {
                resp.setContentType("text/html; charset=utf-8");
                writer = resp.getWriter();
                writer.println("<script type=\"text/javascript\">alert('请求不合法');window.history.back(-1);</script>");
                writer.flush();
                return;
            } catch(IOException e) {
                log.error("请求不合法:{}",e.getMessage());
                return;
            } finally {
                if(null != writer) {
                    writer.close();
                }
            }
        }
        try {
            String path = FileUtil.getFileTemplatePath();
            FileUtil.downloadFile(request,resp,path + fileUrl,fileName);
        } catch(Exception e) {
            try {
                resp.setContentType("text/html; charset=utf-8");
                writer = resp.getWriter();
                writer.println("<script type=\"text/javascript\">alert('文件不存在');window.history.back(-1);</script>");
                writer.flush();
            } catch(IOException ex) {
                log.error("下载发生异常:{}",e.getMessage());
            } finally {
                if(null != writer) {
                    writer.close();
                }
            }
        }
    }
    /**
     * 删除报告
     * @param singleId singleId
     * @param fileUrl fileUrl
     * @return Result
     */
    @DeleteMapping("/azbj/sjtjfx/bgsc/delete/{singleId}")
    public Result deleteFile(@PathVariable String singleId,@RequestParam("fileUrl") String fileUrl) {
        UploadAppendixFile uploadAppendixFile = new UploadAppendixFile();
        //获取单个文件的唯一标识
        uploadAppendixFile.setSingleId(singleId);
        //查询是否有该条目
        UploadAppendixFile uploadFile = uploadAppendixFileFeignService.findAppendixfileOne(uploadAppendixFile);
        if(null == uploadFile) {
            return Result.failure(ReturnCode.FILE_NOT_FOUND);
        }
        String path = FileUtil.getFileTemplatePath();
        File file = new File(path + fileUrl);
        //判断文件是否存在，文件不存在也要删除对应数据库记录
        if(!file.exists()) {
            uploadAppendixFileFeignService.removeAppendixFileOneBySingleId(uploadAppendixFile);
            return Result.success("删除成功！");
        }
        try {
            //如果有删除
            int deleteData = uploadAppendixFileFeignService.removeAppendixFileOneBySingleId(uploadAppendixFile);
            if(Constants.Number.NUM_ZERO < deleteData) {
                boolean delete = file.delete();
                if(delete) {
                    return Result.success("删除成功！");
                } else {
                    return Result.failure(ReturnCode.FILE_NOT_FOUND);
                }
            } else {
                return Result.failure(ReturnCode.DELETE_FAILED);
            }
        } catch(RuntimeException e) {
            log.error("发生异常:",e);
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }
    /**
     * 查询文件列表信息
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param filename filename
     * @param taskId taskId
     * @return String
     */
    @RequestMapping("/azbj/sjtjfx/bgsc/getFilesInfoList")
    public String getFilesInfoList(Integer pageIndex,Integer pageSize,
                                   @RequestParam(required = false, defaultValue = "-1") String filename,
                                   @RequestParam(required = false, defaultValue = "-1") String taskId) {
        UserDTO userDTO = userFacade.getAuthentication();
        String account = userDTO.getAccount();
        Map<String,Object> mapkey = new HashMap<>(16);
        mapkey.put("account",account);
        mapkey.put("taskId",taskId);
        mapkey.put("querykey",filename);
        return statisticService.getFilesInfoList(pageIndex,pageSize,mapkey);
    }
}